package cn.faifai.web.api;

import cn.faifai.common.component.R;
import cn.faifai.common.page.TableDataInfo;
import cn.faifai.tagapi.dto.PageQuery;
import cn.faifai.tagapi.dto.TagDTO;
import cn.faifai.tagapi.dto.TagSerialize;
import cn.faifai.tagapi.entity.Tag;
import cn.faifai.tagapi.repository.TagRepository;
import cn.faifai.tagapi.service.TagService;
import cn.faifai.tagapi.utils.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/tag")
public class TagController {
    @Autowired
    private TagRepository tagRepository;
    @Autowired
    private TagService tagService;

    @PostMapping("/save")
    public R<Tag> save(@RequestBody TagDTO tag){
        return R.ok(tagService.save(tag));
    }

    @PutMapping("/update")
    public R<Tag> update(@RequestBody TagDTO tagDTO) throws IllegalAccessException {
        Tag entity = tagRepository.findById(tagDTO.getId()).orElseThrow(() -> new RuntimeException("Entity not found"));
        BeanUtil.copyPropertiesNonNull(tagDTO,entity);
        return R.ok(tagRepository.save(entity));
    }

    @GetMapping("/oneLayer")
    public R getOneLayerList(TagDTO tagDTO){
        List<Tag> byParentId = tagRepository.findByParentId(tagDTO.getParentId());
        return R.ok(byParentId);
    }

    @DeleteMapping("/{ids}")
    public R delete(@PathVariable("ids") List<Long> ids){
        tagService.delete(ids);
        return R.ok();
    }

    @GetMapping("/list")
    public TableDataInfo<Tag> getTagPageList(TagDTO tagDTO, PageQuery pageQuery){
        return tagService.getTagPageList(tagDTO,pageQuery);
    }

    /**
     * 通过id查询tag
     */
    @GetMapping("/{id}")
    public R<TagSerialize> getTagById(@PathVariable("id") Long id){
        return R.ok(tagService.getTagById(id));
    }


}
